/*
 *   IR Subroutines: Chaos Cube
 *
 */

#include <msp430g2553.h>
#include "ChaosCube.h"

#define IR_PORT 2

const char mirp_data[6] =   { 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF };
const char parity_bit[6] =  { 1,    1,    1,    1,    1,    1    };
char bit_value;

void initIR(void)
{
  P1DIR |= P_IR_DATA;
  P1OUT &= ~P_IR_DATA;

  TA1CCR0 = 69;				              // Timer delay for LED flash, 1/56kHz = 69 / 8 MHz
  TA1CTL = TASSEL_2 + MC_1 + TACLR;       // SMCLK, up mode, clear timer

} // End of initIR


void sendIR(int face)
{
  char mirp_byte = mirp_data[face - 2];
  int mirp_bit = 0;

  while(mirp_bit < 11) {

    /* Choose Transmission Bit Value */
    if( mirp_bit == 0 ){
      bit_value = 1;
    }

    else if( mirp_bit == 1 ) {
      bit_value = 0;
    }

    else if( mirp_bit == 10){
      bit_value = (parity_bit[face - 2] & 0x1);
    }

    else{
      bit_value = (mirp_byte >> (7 - (mirp_bit - 2))) & 0x1;   // Set to next bit in payload
    }

    /* Transmit MIRP Data */
    TA1CCTL0 |= CCIE;

    P1OUT &= ~P_IR_DATA;                      // Force IR low
    __delay_cycles(388 * delay_us);           // Allow transmission for 1/2 ms (500us - 2us per interrupt)
    TA1CCTL0 &= ~CCIE;
    P1OUT &= ~P_IR_DATA;
    __delay_cycles(2800 * delay_us);          // Wait remaining bit period
    mirp_bit += 1;
  }

  P1OUT &= ~P_IR_DATA;
  bit_value = 0;
  mirp_bit = 0;
} //End of sendIR



/* Interrupt Service Routine */

#pragma vector = TIMER1_A0_VECTOR
__interrupt void TA1_CCR0_ISR(void)
{

	P1OUT ^= (bit_value << IR_PORT);

} // TA1_CCR0_ISR
